﻿using System;
using System.Web;
using System.Web.Mvc;
using Utils.Commons;
using Utils.Helpers;

namespace sc.user.com.Controllers
{
    public class LoginAuthController : RedirectHelper
    {
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="username"></param>
        /// <param name="psd"></param>
        /// <returns></returns>
        // GET: LoginAuth
        public ActionResult Login(string username, string psd)
        {
            if(string.IsNullOrEmpty(username) && string.IsNullOrEmpty(psd))
                throw new Exception("请输入用户名与密码");

            var token = $"Jwt:{username}{psd}";
            //设置session
            Session[StaticString.Token] = token;

            //设置Cookie
            var cookie = new HttpCookie(StaticString.Token)
            {
                HttpOnly = true,
                Expires = DateTime.Now.AddMinutes(1),//永不过期
                Value = token
            };
            Response.Cookies.Add(cookie);

            //登录通知到子域站点
            var currentUrl = "https://localhost:44327";
            var trustedSites = System.Configuration.ConfigurationManager.AppSettings["TrustedSitesAuth"].ToString();
            return RedirectNotice(currentUrl, token, trustedSites);
        }

        /// <summary>
        /// 单点登录与单点退出
        /// </summary>
        /// <param name="sourceUrl"></param>
        /// <param name="token"></param>
        /// <param name="trustedSites"></param>
        /// <returns></returns>
        public ActionResult Auth(string sourceUrl, string token, string trustedSites = null)
        {
            //设置session
            Session[StaticString.Token] = token;

            //设置Cookie
            var cookie = new HttpCookie(StaticString.Token)
            {
                HttpOnly = true,
                Expires = string.IsNullOrEmpty(token) //如果token为空则将cookie设置过期
                    ? DateTime.MinValue
                    : DateTime.Now.AddMinutes(30),
                Value = token
            };
            Response.Cookies.Add(cookie);

            return RedirectNotice(sourceUrl, token, trustedSites);
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginOut()
        {
            //删除Session Token
            Session[StaticString.Token] = "";
            //删除Cookie Token
            Response.Cookies[StaticString.Token].Expires = DateTime.MinValue;

            //退出通知到子域站点
            var currentUrl = System.Configuration.ConfigurationManager.AppSettings["OneselfWebSite"].ToString() + "/LoginAuth/Index";
            var trustedSites = System.Configuration.ConfigurationManager.AppSettings["TrustedSitesAuth"].ToString();
            return RedirectNotice(currentUrl, string.Empty, trustedSites);
        }
    }
}